package com.sdp.wz.controller;


import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.wz.db.wz_info.entity.WzInfo;
import com.sdp.wz.db.wz_info.service.IWzInfoService;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-07-29
 */
@RestController
@RequestMapping("/WzInfoController")
public class WzInfoController {

	@Autowired
	private Query query;
	
	@Autowired
	private IWzInfoService iWzInfoService;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iWzInfoService, WzInfo.class, dataCenter));
	}
	
	@GetMapping(value = "/queryWzInfoByWzNo")
	public Result<?> queryWzInfoByWzNo(@RequestParam(name="wzNo",required=true) String wzNo) {
		if(StringUtils.isEmpty(wzNo)) {
			return Result.error("物资编码为空");
		}
		return Result.ok(iWzInfoService.queryWzInfoByWzNo(wzNo));
	}
	
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody WzInfo wzInfo) {
		if(wzInfo==null) {
			return Result.error("物资信息为空");
		}
		if(StringUtils.isEmpty(wzInfo.getKeyId())) {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWzInfoService, WzInfo.class, new String[] {"wzNo","wzName"}, "keyId", wzInfo, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("物资编号和名称不能重复");
			}
			wzInfo.setCreateTime(LocalDateTime.now());
			iWzInfoService.save(wzInfo);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iWzInfoService, WzInfo.class, new String[] {"wzNo","wzName"}, "keyId", null, wzInfo, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("物资编号和名称不能重复");
			}
			iWzInfoService.updateById(wzInfo);
		}
		
		return Result.ok();
	}
}

